import 'package:cupertino_store/model/app_state_model.dart';
import 'package:cupertino_store/product_row_item.dart';
import 'package:cupertino_store/styles.dart';
import 'package:flutter/cupertino.dart';
import 'package:intl/intl.dart';
import 'package:provider/provider.dart';

class ShoppingCartTab extends StatefulWidget {
  const ShoppingCartTab({super.key});

  @override
  State<StatefulWidget> createState() {
    return _CartTabState();
  }
}

const double _kDateTimePickerHeight = 216;  // NEW


class _CartTabState extends State <ShoppingCartTab> {
   late String name;
   late String email;
   late String location;
   DateTime dateTime = DateTime.now();
   final _currencyFormat = NumberFormat.currency(symbol: '\$');

   Widget _buildNameTextFiled() {
     return CupertinoTextField(
      prefix: const Icon(
        CupertinoIcons.person_solid,
        color: CupertinoColors.lightBackgroundGray,
        size: 25,
      ),
      padding: const EdgeInsets.symmetric(horizontal: 6,vertical: 12),
      clearButtonMode: OverlayVisibilityMode.editing,
      textCapitalization: TextCapitalization.words,
      autocorrect: false,
      placeholder: 'Name',
      onChanged: (value) {
        setState(() {
          name = value;
        });
      },
      decoration: const BoxDecoration(
        border: Border(
          bottom: BorderSide(
            width: 0,
            color: CupertinoColors.inactiveGray,
          ),
        ),
      ),
     );
   }

   Widget _buildEmailTextFiled(){
    return CupertinoTextField(
      prefix: const Icon(
        CupertinoIcons.mail_solid,
        color: CupertinoColors.lightBackgroundGray,
        size: 25,
      ),
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 12),
      clearButtonMode: OverlayVisibilityMode.editing,
      textCapitalization: TextCapitalization.words,
      keyboardType: TextInputType.emailAddress,
      placeholder: 'Email address',
      onChanged: (value) {
        setState(() {
          email = value;
        });
      },
      decoration: const BoxDecoration(
        border: Border(
          bottom: BorderSide(
            width: 0,
            color: CupertinoColors.inactiveGray,
          ),
        ),
      ),
    );
   }

  Widget _buildLocalTextFiled(){
    return CupertinoTextField(
      prefix: const Icon(
        CupertinoIcons.location_solid,
        color: CupertinoColors.lightBackgroundGray,
        size: 25,
      ),
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 12),
      clearButtonMode: OverlayVisibilityMode.editing,
      textCapitalization: TextCapitalization.words,
      placeholder: 'Location address',
      onChanged: (value) {
        setState(() {
          location = value;
        });
      },
      decoration: const BoxDecoration(
        border: Border(
          bottom: BorderSide(
            width: 0,
            color: CupertinoColors.inactiveGray,
          ),
        ),
      ),
    );
  }

  Widget _buildDatePicker() {
    return Column(
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
           const Row(
              children: [
                Icon(
                  CupertinoIcons.clock,
                  color: CupertinoColors.lightBackgroundGray,
                  size: 25,
                ),
                SizedBox(width: 6,),
                Text('Delivery time', style: Styles.deliveryTimeLabel)
              ],
            ),
            Text(DateFormat.yMMMd().add_jm().format(dateTime), style: Styles.deliveryTime)
          ],
        ),
       SizedBox(
          height: _kDateTimePickerHeight,
          child: CupertinoDatePicker(
            mode: CupertinoDatePickerMode.date,
            maximumDate: DateTime.now(),
            initialDateTime: dateTime,
            use24hFormat: true,
            onDateTimeChanged: (newDateTime) {
              setState(() {
                dateTime = newDateTime;
              });
            },
          ),
        ),
      ],
    );
  }

  SliverChildBuilderDelegate _sliverChildBuilderDelegate(AppStateModel model){
    return SliverChildBuilderDelegate((context, index) {
      final productIndex = index - 4;
      switch (index) {
        case 0:
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 5),
            child: _buildNameTextFiled(),
          );
        case 1:
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 5), 
            child: _buildEmailTextFiled(),
          );
        case 2:
          return Padding(
            padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 5), 
            child: _buildLocalTextFiled(),
          );
        case 3:
        return Padding(
          padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 5),
          child: _buildDatePicker()
        );
        default:
        if (model.productsInCart.length > productIndex){
          return ProductRowItem(product: model.getProductById(model.productsInCart.keys.toList()[productIndex]), index: index, lastItem: productIndex == model.productsInCart.length - 1);
        }else if (model.productsInCart.keys.length == productIndex && model.productsInCart.isNotEmpty) {
          return Padding(
            padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Column(
                  mainAxisAlignment: MainAxisAlignment.end,
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text(
                          'Shipping '
                          '${_currencyFormat.format(model.shippingCost)}',
                          style: Styles.productRowItemPrice,
                        ),
                    const SizedBox(height: 6,),
                    Text(
                      'Tax ${_currencyFormat.format(model.tax)}',
                      style: Styles.productRowItemPrice,
                    ),
                    const SizedBox(height: 6,),
                    Text(
                      'Total ${_currencyFormat.format(model.totalCost)}',
                      style: Styles.productRowItemPrice,
                    ),
                  ],
                ),
              ],
            ),
          );
        }
        
      }
      return null;
    });
  }
  @override
  Widget build(BuildContext context) {
    return Consumer <AppStateModel>(
      builder:(context, model, child){
        return CustomScrollView(
          slivers: [
           const CupertinoSliverNavigationBar(
              largeTitle: Text('ShoppingCart'),
            ),
            SliverSafeArea(
              top: false,
              minimum: const EdgeInsets.only(top: 4),
              sliver: SliverList(delegate: _sliverChildBuilderDelegate(model)),
            ),
          ],
        );
      }
    );
  }

}